const  readfileAndWrite =require( './readfileAndWrite');
const fs = require("fs")
const path = require('path');
const join = path.join
const UrlPattern = require("url-pattern")
const lodash=require('lodash')
var ignores = [
    ".vsvode",
    '.git',
    'node_modules',
    '.idea',
    'ps\\替他秀长图--.psd',
    'show\\模拟show的目录结构逃离jsp',
    '.nojekyll',
    '.gitignore',
    'book.js',
    'images',
    '_sidebar',
    '_navbar',
    '_coverpage',
];


function matchIgnores(str, ignores) {
    var isIn = false;
    return ignores.findIndex(item => {
        return str.indexOf(item) >= 0
    }) >= 0
}

function getJsonFiles(jsonPath, ignores) {
    let jsonFiles = [];

    function findJsonFile(path, ignores) {
        let files = fs.readdirSync(path);
        files.forEach(function (item, index) {
            let fPath = join(path, item);
            let stat = fs.statSync(fPath);
            if (stat.isDirectory() === true) {
                findJsonFile(fPath, ignores);
            }
            if (stat.isFile() === true) {
                //排除
                /*  if (ignores &&

                  ) {

                  }*/
                var isTrue = ignores &&
                    matchIgnores(path, ignores)
                if (!isTrue) {
                    jsonFiles.push(fPath);
                }
            }
        });
    }

    findJsonFile(jsonPath, ignores);
    // console.log(jsonFiles);
    var paths = {}
    jsonFiles.forEach((path, index) => {
        if (path.indexOf("\\") >= 0) {
            var parent=path.split("\\")[0]
            var children=path.split("\\")[1]
            if(!paths[parent]){
                paths[parent]=[]
            }
            //如果不是md结尾 不要
            if(children.indexOf('.md')>0){
                paths[parent].push(children)
            }

        }
    })

    var strHtml=``
    lodash.map(paths,(item,key)=>{
        var parentHtml=`* [${key}](./)\n`
        item.map(child=>{
            parentHtml+=`  * [${child}](./${key}/${child}) \n`
        })
        strHtml+=`${parentHtml}\n`
    })
    console.log("=========!!!!!!!!!!!!!!!!!!!=======================")
    // console.log(strHtml)
    readfileAndWrite(strHtml,'_sidebar.md')
}

getJsonFiles("./", ignores);